package sign_in.loginsystem.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sign_in.loginsystem.model.entity.User;
import sign_in.loginsystem.model.util.Result;
import sign_in.loginsystem.service.port.AccountService;
import sign_in.loginsystem.service.port.AdminService;
import sign_in.loginsystem.tool.Analyze;

import java.io.File;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {



    @Autowired
    Analyze analyze;


    @Autowired
    AccountService accountService;

    @Autowired
    AdminService adminService;


    @PostMapping("/upload")
    public Result uploadAvatar(@RequestHeader("Token")String token,
                               @RequestParam(value = "file") MultipartFile file) throws Exception {
        String catalogue = "D:\\java code\\project\\ultimately\\LoginSystem\\image\\";
        User user = analyze.analyzeToken(token);
        if (user.getAvatar()!=null){
            System.out.println(catalogue+user.getAvatar());
            File file1 = new File(catalogue+user.getAvatar());
            if (!file1.delete()){
                System.out.println("删除失败");
            }
        }
        String orgName = file.getOriginalFilename();
        int index = 0;
        if (orgName != null) {
            index = orgName.lastIndexOf(".");
        }
        if (index==-1){
            return Result.error(null);
        }
        String extname = null;
        if (orgName != null) {
            extname = orgName.substring(index);
        }
        UUID uuid = UUID.randomUUID();
        String nuwFileName = uuid +extname;
        user.setAvatar(nuwFileName);
        file.transferTo(new File(catalogue+nuwFileName));
        return accountService.editAccount(user,user);
    }



}
